package stu.aistar.config;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.Data;

import org.springframework.stereotype.Component;
import stu.aistar.model.vo.PayVo;
import stu.aistar.util.PropertiesUtil;

/**
 * *类名：AlipayConfig
 *  *功能：基础配置类
 *  *详细：设置帐户有关信息及返回路径
 */

@Component
@Data
public class AlipayConfig {

    public static String pay(PayVo vo) throws AlipayApiException {

        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient=new DefaultAlipayClient(
                //支付宝网关
                PropertiesUtil.getKey("gatewayUrl"),
                //appid
                PropertiesUtil.getKey("app_id"),
                //商户私钥
                PropertiesUtil.getKey("merchant_private_key"),
                "json",
                //字符编码格式
                PropertiesUtil.getKey("charset"),
                //支付宝公钥
                PropertiesUtil.getKey("alipay_public_key"),
                //签名方式
                PropertiesUtil.getKey("sign_type")
        );

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest=new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(PropertiesUtil.getKey("return_url"));
        alipayRequest.setNotifyUrl(PropertiesUtil.getKey("notify_url"));

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = String.valueOf(vo.getPrice());
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result=alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应："+result);
        return result;
    }

}
